package com.heroCW.bodhiAttic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heroCW.bodhiAttic.exception.CustomException;
import com.heroCW.bodhiAttic.dto.DishDto;
import com.heroCW.bodhiAttic.entity.Category;
import com.heroCW.bodhiAttic.entity.Dish;
import com.heroCW.bodhiAttic.entity.DishFlavor;
import com.heroCW.bodhiAttic.entity.SetmealDish;
import com.heroCW.bodhiAttic.mapper.DishMapper;
import com.heroCW.bodhiAttic.resultUtil.ResultCode;
import com.heroCW.bodhiAttic.service.CategoryService;
import com.heroCW.bodhiAttic.service.DishFlavorService;
import com.heroCW.bodhiAttic.service.DishService;
import com.heroCW.bodhiAttic.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品，同时保存菜品对应的口味数据
     *
     * @param dishDto
     */
    @Override
    @Transactional
    public Boolean saveWithFlavor(DishDto dishDto) {

        // 菜品ID
        Long dtoId = dishDto.getId();

        // 菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();

        // flavors.forEach(f -> f.setDishId(dtoId));
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dtoId);
            return item;
        }).collect(Collectors.toList());
        // 保存菜品口味数据到菜品口味表
        dishFlavorService.saveBatch(flavors);

        // 保存菜品的基本信息到菜品表dish
        return this.save(dishDto);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        // 查询菜品的基本信息
        Dish dish = this.getById(id);

        if (dish == null) {
            throw new CustomException(ResultCode.CUSTOM_CANNOT_QUERY_ERR, "暂时无法查询菜品信息，请刷新再试");
        }

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        // 查询菜品的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());

        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);

        dishDto.setFlavors(flavors);
        log.info("dishDto: {}", dishDto);
        return dishDto;
    }

    /**
     * 修改菜品，同时修改菜品对应的口味数据
     *
     * @param dishDto
     */
    @Override
    @Transactional
    public Boolean updateWithFlavor(DishDto dishDto) {
        // 更新dish表基本信息
        Boolean[] flags = new Boolean[2];
        flags[0]= this.updateById(dishDto);

        // 清理当前菜品对应口味数据
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());

        dishFlavorService.remove(queryWrapper);

        // 添加当前提交过来的口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        flags[1]= dishFlavorService.saveBatch(flavors);

        for (Boolean flag : flags) {
            if (!flag)
                return false;
        }
        return true;
    }

    /**
     * 删除菜品及其对应口味数据
     *
     * @param ids
     */
    @Override
    @Transactional
    public Boolean removeDishWithFlavor(List<Long> ids) {
        // 查询套装状态
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.in(Dish::getId, ids);
        dishWrapper.eq(Dish::getStatus, 1);
        int dishCount = this.count(dishWrapper);
        // 查出数据，不能删除
        if (dishCount > 0) {
            throw new CustomException(ResultCode.CUSTOM_CANNOT_DELETE_ERR, "当前菜品正在售卖中，不能删除");
        }

        LambdaQueryWrapper<SetmealDish> setmealDish0Wrapper = new LambdaQueryWrapper<>();
        setmealDish0Wrapper.in(SetmealDish::getDishId, ids);
        int setmealDishCount = setmealDishService.count(setmealDish0Wrapper);
        // 查出数据，不能删除
        if (setmealDishCount > 0) {
            throw new CustomException(ResultCode.CUSTOM_CANNOT_DELETE_ERR, "当前菜品关联了套餐，不能删除");
        }

        // for (Long id : ids) {}
        // 清理当前菜品对应口味数据
        LambdaQueryWrapper<DishFlavor> dishFlavorWrapper = new LambdaQueryWrapper<>();
        dishFlavorWrapper.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(dishFlavorWrapper);

        //删除当前菜品
        return this.removeByIds(ids);
    }

    /**
     * 修改菜品状态
     *
     * @param status
     * @param ids
     */
    @Override
    @Transactional
    public Boolean updateStatus(Integer status, List<Long> ids) {

        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Dish::getId, ids);
        updateWrapper.set(Dish::getStatus, status);

        // 方法2 重载成update(Object, Wrapper)
        return this.update(new Dish(), updateWrapper);
    }

    @Override
    public IPage<DishDto> getPage(int page, int pageSize, String name) {
        IPage<Dish> pageInfo = new Page<>(page, pageSize);
        IPage<DishDto> dishDtoPage = new Page<>();
        // select * from dish where name like '%_%' or
        //        category_id in (select id from category where name like '%_%') order by update_time limit ?, ?
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotEmpty(name)) {

            dishWrapper.like(Dish::getName, name);

            List<Long> longList = categoryService.getIdsLikeName(name);

            if (!longList.isEmpty()) {
                dishWrapper.or();
                dishWrapper.in(Dish::getCategoryId, longList);
            }
        }

        dishWrapper.orderByDesc(Dish::getUpdateTime);

        this.page(pageInfo, dishWrapper);

        // 对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = this.copyToDishDto(records);
        dishDtoPage.setRecords(list);
        return dishDtoPage;
    }

    @Override
    public List<DishDto> getList(Dish dish) {
        // 构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.like(dish.getName() != null, Dish::getName, dish.getName());
        // 查询状态为1，即启售
        queryWrapper.eq(Dish::getStatus, 1);
        // 添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = this.list(queryWrapper);

        return this.copyToDishDto(list);
    }

    @Override
    public List<DishDto> copyToDishDto(List<Dish> list) {
        return list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();

            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            // 检查当前菜品的Id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
    }
}
